<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Region, Riderlist, RiderStreet, Order, Orderlog, Graborder, Message, CateSons, AreaPrice, Exchange};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;
use EasyWeChat\Factory;

class Rider extends Base
{
    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '登录手机号不能为空',
            'password.require' => '登录密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where('mobile', $data['mobile'])->find();
        $token = 'RIDER' . md5(md5($user['id'] . time()));
        if ($user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '密码错误');
        }
        Redis::setex($token, 86400 * 7, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function orderlist()
    {
        $list = (new Order())->order('id desc');
        $status = $this->request->get('status/d', 1);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        if ($status == 1) {
            $street = (new RiderStreet())->where(['riderid' =>  $this->request->reder_id, 'status' => 2])->column('street');
            if (empty($street)) {
                $this->result($list, 0, '获取成功');
            }
            $list = $list->where(['street' => $street]);
        } else {
            $list = $list->where('orders_id', $this->request->reder_id);
        }
        $list = $list->field('id,user_id,ordersn,status,created,appointment,province,city,area,street,address,lon,lat,total,info,ispublic,mobile,name,posaddress')
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
            $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
            $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
            $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            $lists['orderlog'] = (new Orderlog())->where('ordersn', $lists['ordersn'])->field('id,name,icon,number,areapriceid,money,units,unit,price')->select();
            $lists['total'] = 0;
            if ($lists['status'] == 1 || $lists['status'] == 2) {
                foreach ($lists['orderlog'] as $orderlog) {
                    $lists['total'] += $orderlog['number'] * $orderlog['money'];
                }
            }
            if ($lists['status'] == 3 || $lists['status'] == 4 || $lists['status'] == 5) {
                foreach ($lists['orderlog'] as $orderlog) {
                    $lists['total'] += $orderlog['price'] * $orderlog['units'];
                }
            }
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待接单';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '已接单';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '待付款';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 5) {
                $lists['status_text'] = '待评价';
            }
            if ($lists['status'] == 6) {
                $lists['status_text'] = '已取消';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderuplon()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'lon' => 'require',
            'lat' => 'require',

        ], [
            'lon.require' => '坐标不能为空',
            'lat.require' => '坐标不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $res = (new Riderlist())->where('id', $this->request->reder_id)->update(['riderlon' => $data['lon'], 'riderlat' => $data['lat']]);
        if ($res) {
            $this->result([], 0, '更新成功');
        }
        $this->result([], 1, '更新失败');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new Order())->where(['id' => $id])
            ->field('id,ordersn,status,orders_id,user_id,created,appointment,province,city,area,street,address,lon,lat,total,info,ispublic,mobile,name,riderlon,riderlat,posaddress,star,content')->find();
        if (empty($lists)) {
            $this->result([], 1, '获取失败');
        }
        $rider = (new Riderlist())->where('id', $lists['orders_id'])->find();
        $lists['riderlon'] = $rider['riderlon'];
        $lists['riderlat'] = $rider['riderlat'];
        $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
        $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
        $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
        $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
        $lists['orderlog'] = (new Orderlog())->where('ordersn', $lists['ordersn'])->field('id,name,icon,number,areapriceid,money,price,units,unit')->select();
        $lists['total'] = 0;
        if ($lists['status'] == 1 || $lists['status'] == 2) {
            foreach ($lists['orderlog'] as $orderlog) {
                $lists['total'] += $orderlog['number'] * $orderlog['money'];
            }
        }
        if ($lists['status'] == 3 || $lists['status'] == 4 || $lists['status'] == 5) {
            foreach ($lists['orderlog'] as $orderlog) {
                $lists['total'] += $orderlog['price'] * $orderlog['units'];
            }
        }
        if ($lists['status'] == 1) {
            $lists['status_text'] = '待接单';
        }
        if ($lists['status'] == 2) {
            $lists['status_text'] = '已接单';
        }
        if ($lists['status'] == 3) {
            $lists['status_text'] = '待付款';
        }
        if ($lists['status'] == 4) {
            $lists['status_text'] = '已完成';
        }
        if ($lists['status'] == 5) {
            $lists['status_text'] = '待评价';
        }
        if ($lists['status'] == 6) {
            $lists['status_text'] = '已取消';
        }
        $this->result($lists, 0, '获取成功');
    }

    public function orders()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where(['id' => $id])->find();
        if (empty($list)) {
            $this->result([], 1, '订单数据不存在');
        }
        if ($list['status'] != 1) {
            $this->result([], 1, '订单已接单或取消');
        }
        //判断是否为自己街道订单
        $riderstreet = (new RiderStreet())->where(['riderid' =>  $this->request->reder_id, 'street' => $list['street'], 'status' => 2])->find();
        if (empty($riderstreet)) {
            $this->result([], 1, '您不属于该街道，无法接单');
        }
        $unique = 'riderorders' . $id;
        $frtimes = Redis::get($unique);
        if ($frtimes) {
            $timerds = Redis::ttl($unique);
            $this->result([], 1, '为避免重复抢单,请' . $timerds . '秒后再试');
        } else {
            Redis::setex($unique, 2, 2);
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $id, 'status' => 1])->update(['status' => 2, 'orders_id' => $this->request->reder_id, 'ordertime' => date('Y-m-d')]);
            (new Graborder())->insert(['user_id' => $this->request->reder_id, 'orderid' => $id, 'type' => 1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '接单失败，请重试');
        }
        $this->result([], 0, '接单成功');
    }

    public function riderstreet()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'province' => 'require',
                'city' => 'require',
                'area' => 'require',
                'street' => 'require'
            ], [
                'province.require' => '省份ID不能为空',
                'city.require' => '城市ID不能为空',
                'area.require' => '区域ID不能为空',
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //判断是否存在该街道记录
            $RiderStreet = (new RiderStreet())->where(['riderid' => $this->request->reder_id, 'street' => $data['street']])->find();
            if (!empty($RiderStreet) && $RiderStreet['status'] == 2) {
                $this->result([], 1, '您已是该街道的家政人员，无需重复申请');
            }
            if (!empty($RiderStreet) && $RiderStreet['status'] == 1) {
                $this->result([], 1, '该街道的申请待合伙人审核，无需重复申请');
            }
            //查省市区是否存在
            $province = (new Region())->where(['area_code' => $data['province'], 'level' => 1])->find();
            if (empty($province)) {
                $this->result([], 1, '省份编号错误');
            }
            $city = (new Region())->where(['area_code' => $data['city'], 'level' => 2, 'parent_id' => $province['id']])->find();
            if (empty($city)) {
                $this->result([], 1, '城市编号错误');
            }
            $area = (new Region())->where(['area_code' => $data['area'], 'level' => 3, 'parent_id' => $city['id']])->find();
            if (empty($area)) {
                $this->result([], 1, '区域编号错误');
            }
            $street = (new Region())->where(['id' => $data['street'], 'level' => 4, 'parent_id' => $area['id']])->find();
            if (empty($street)) {
                $this->result([], 1, '街道ID错误');
            }
            Db::startTrans();
            try {
                if (!empty($RiderStreet)) {
                    (new RiderStreet())->where('id', $RiderStreet['id'])->update([
                        'riderid' => $this->request->reder_id,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                } else {
                    (new RiderStreet())->insert([
                        'riderid' => $this->request->reder_id,
                        'provinceid' => $data['province'],
                        'cityid' => $data['city'],
                        'areaid' => $data['area'],
                        'street' => $data['street'],
                        'status' => 1
                    ]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        } else {
            $list = (new RiderStreet())->field('provinceid,cityid,areaid,street,status')->where(['riderid' => $this->request->reder_id])->select();
            foreach ($list as $lists) {
                $lists['province_text'] = (new Region())->where(['area_code' => $lists['provinceid']])->value('name');
                $lists['city_text'] = (new Region())->where(['area_code' => $lists['cityid']])->value('name');
                $lists['area_text'] = (new Region())->where(['area_code' => $lists['areaid']])->value('name');
                $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function setmobile()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'mobile' => 'require',
                'code' => 'require'
            ], [
                'mobile.require' => '手机号不能为空',
                'code.require' => '验证码不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!preg_match("/^1[345678]{1}\d{9}$/", $data['mobile'])) {
                $this->result([], 1, '手机号码格式不正确');
            }
            $riderlist = (new Riderlist())->where('id', $this->request->reder_id)->find();
            if ($riderlist['mobile'] == $data['mobile']) {
                $this->result([], 1, '更改手机号码不能与原手机号码一致');
            }
            //识别验证码是否正确
            if (!(new Mns())->checkCode($data['code'], $riderlist['mobile'])) {
                $this->result([], 1, '手机验证码错误');
            }
            //查找手机号码是否重复
            $havelist = (new Riderlist())->where('mobile', $data['mobile'])->find();
            if (!empty($havelist) && $havelist['id'] != $this->request->reder_id) {
                $this->result([], 1, '该手机号码已被使用');
            }
            Db::startTrans();
            try {
                (new Riderlist())->where('id', $this->request->reder_id)->update(['mobile' => $data['mobile']]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        }
    }


    public function setpassword()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'password' => 'require',
                'code' => 'require'
            ], [
                'password.require' => '密码不能为空',
                'code.require' => '验证码不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //识别验证码是否正确
            $riderlist = (new Riderlist())->where('id', $this->request->reder_id)->find();
            if (!(new Mns())->checkCode($data['code'], $riderlist['mobile'])) {
                $this->result([], 1, '手机验证码错误');
            }
            if ($riderlist['password'] == md5(md5($data['password']))) {
                $this->result([], 0, '修改成功');
            }
            Db::startTrans();
            try {
                (new Riderlist())->where('id', $this->request->reder_id)->update(['password' => md5(md5($data['password']))]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '修改失败，请重试');
            }
            $this->result([], 0, '修改成功');
        }
    }


    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'mobile' =>  'require',
            ], [
                'message.require' => '反馈信息不能为空',
                'mobile.require' => '联系电话不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['type'] = 2;
            $data['user_id'] = $this->request->reder_id;
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->reder_id, 'type' => 2])
                ->field('message,reply,created')
                ->paginate(20, false, ['query' => $this->request->param()]);
            $this->result($list, 0, '查询完成');
        }
    }

    public function serrider()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'mobile' =>  'require',
        ], [
            'mobile.require' => '手机号码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $list = (new Riderlist())->where('mobile', 'like', '%' . $data['mobile'] . '%')->field('id,mobile,name')->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '查询完成');
    }


    public function  returnorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'orderid' => 'require',
                'userid' =>  'require',
            ], [
                'orderid.require' => '订单编号不能为空',
                'userid.require' => '用户编号不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查看订单是否存在
            $order = (new Order())->where(['id' => $data['orderid'], 'status' => 2, 'orders_id' => $this->request->reder_id])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不存在或不可转让');
            }
            if ($data['userid'] == $this->request->reder_id) {
                $this->result([], 1, '不可以转让给自己');
            }
            $user = (new Riderlist())->where(['id' => $data['userid']])->find();
            if (empty($user)) {
                $this->result([], 1, '转让用户不存在');
            }
            if ($user['status'] != 1) {
                $this->result([], 1, '转让用户繁忙或下线');
            }
            //判断用户是否存在或有没有接单权限
            $RiderStreet = (new RiderStreet())->where(['riderid' => $data['userid'], 'status' => 2, 'street' => $order['street']])->find();
            if (empty($RiderStreet)) {
                $this->result([], 1, '无订单所属街道接单权限');
            }
            Db::startTrans();
            try {
                (new Order())->where(['id' => $data['orderid'], 'status' => 2])->update(['orders_id' => $data['userid'], 'ordertime' => date('Y-m-d')]);
                (new Graborder())->insert(['user_id' => $data['userid'], 'comeuser_id' => $this->request->reder_id, 'orderid' => $order['id'], 'type' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '修转让失败，请重试');
            }
            $this->result([], 0, '转让成功');
        }
    }

    public function ordercancel()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where(['id' => $id, 'orders_id' => $this->request->reder_id])->find();
        if (empty($list)) {
            $this->result([], 1, '订单数据不存在');
        }
        if ($list['status'] != 3) {
            $this->result([], 1, '订单不可取消');
        }
        $res = (new Order())->where(['id' => $list['id']])->update(['status' => 6]);
        if ($res) {
            $this->result([], 1, '取消成功');
        }
        $this->result([], 1, '取消失败，请重试');
    }

    public function confirmorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'orderid' => 'require',
            'data' =>  'require',
            'payment' => 'require|in:1,2'
        ], [
            'orderid.require' => '订单id不能为空',
            'data.require' => '数据不能为空',
            'payment.require' => '付款方式不能为空',
            'payment.in' => '付款类型不正确'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $datarr = json_decode($data['data'], true);
        if (empty($datarr)) {
            $this->result([], 1, '数据格式错误');
        }
        $list = (new Order())->where(['id' => $data['orderid'], 'orders_id' => $this->request->reder_id])->find();
        if (empty($list)) {
            $this->result([], 1, '无权操作改订单');
        }
        if ($list['status'] != 2 && $list['status'] != 3) {
            $this->result([], 1, '订单状态不可更改');
        }
        $total = 0;
        $savearr = [];
        foreach ($datarr as $datas) {
            if (empty($datas['id']) || empty($datas['price']) || empty($datas['units'])) {
                $this->result([], 1, '数据参数错误');
            }
            $datas['units'] = (int)$datas['units'];
            if ($datas['units'] <= 0) {
                $this->result([], 1, '填写数量不能为空');
            }
            $datas['total'] = round($datas['units'] * $datas['price'], 2);
            $orderlog = (new Orderlog())->where(['id' => $datas['id'], 'ordersn' => $list['ordersn']])->find();
            if (empty($orderlog)) {
                $this->result([], 1, '数据编号出错，该编号不属于该订单');
            }
            $total += $datas['total'];
            $savearr[] = $datas;
        }
        $unique = 'riderorders' . $data['orderid'];
        $frtimes = Redis::get($unique);
        if ($frtimes) {
            $timerds = Redis::ttl($unique);
            $this->result([], 1, '为避免重复结单,请' . $timerds . '秒后再试');
        } else {
            Redis::setex($unique, 2, 2);
        }
        Db::startTrans();
        try {
            //1表示线下支付直接完结
            if ($data['payment'] == 1) {
                (new Order())->where(['id' => $data['orderid']])->update(['status' => 5, 'total' => $total, 'paytime' => date('Y-m-d H:i:s')]);
            } else {
                (new Order())->where(['id' => $data['orderid']])->update(['status' => 3, 'total' => $total]);
            }
            (new Orderlog())->allowfield(true)->saveAll($savearr);
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $list = (new Order())->where(['orders_id' => $this->request->reder_id, 'status' => 2])->count();
        $this->result($list, 0, '操作成功');
    }

    public function rank()
    {
        $result = [
            'ordercount' => 0, //接单总量
            'todayorder' => 0, //今日接单量
            'orderrank' => '--', //接单排行
            'ordertotal' => 0, //总价
            'todaytotal' => 0, //今日价
            'totalrank' => '--' //价格排行
        ];
        //获取自己的所有订单数据
        $order = (new Order())->where(['orders_id' => $this->request->reder_id])->select();
        foreach ($order as $orders) {
            $result['ordercount'] += 1;
            $result['ordertotal'] += $orders['total'];
            if ($orders['ordertime'] == date('Y-m-d')) {
                $result['todayorder'] += 1;
                $result['todaytotal'] += $orders['total'];
            }
        }
        $ordercount = Redis::zRevRank('ordercount', $this->request->reder_id);
        if ($ordercount !== false) {
            $result['orderrank'] = $ordercount + 1;
        }
        $ordertotal = Redis::zRevRank('ordertotal', $this->request->reder_id);
        if ($ordertotal !== false) {
            $result['totalrank'] = $ordertotal + 1;
        }
        $this->result($result, 0, '获取成功');
    }

    public function getstatus()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'status' => 'require|in:1,2,3'
        ], [
            'status.require' => '状态类型不能为空',
            'status.in' => '状态类型错误'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where(['id' => $this->request->reder_id])->find();
        if ($user['status'] == $data['status']) {
            $this->result([], 1, '状态未更改');
        }
        $res = (new Riderlist())->where(['id' => $this->request->reder_id])->update(['status' => $data['status']]);
        if ($res) {
            $this->result([], 0, '更改成功');
        }
        $this->result([], 1, '更改失败，请重试');
    }

    public function getinfo()
    {

        $user = (new Riderlist())->field('id,mobile,name,cards,status,openid')->where(['id' => $this->request->reder_id])->find();
        $this->result($user, 0, '获取成功');
    }

    public function getOpenId()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'code' => 'require',
            'mobile' => 'require',
            // 'state' => 'require'
        ], [
            'code.require' => 'code不能为空',
            'mobile.require' => '绑定手机号不能为空',
            // 'state.require' => '验证码必须填写',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
        $results = ['status' => 1, 'info' => '授权失败!'];
        if (empty($user)) {
            $results = ['status' => 1, 'info' => '账号不存在,请确保手机号码正确!'];
            return view(null, ['list' => $results]);
        }
        //识别验证码是否正确
        // if (!(new Mns())->checkCode($data['state'], $data['mobile'])) {
        //     $results = ['status' => 1, 'info' => '手机验证码错误!'];
        //     return view(null, ['list' => $results]);
        // }
        // if (!empty($user['openid'])) {
        //     $results = ['status' => 0, 'info' => '用户已授权，无需重复授权!'];
        //     return view(null, ['list' => $results]);
        // }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (!empty($wxuser['id'])) {
                if (!empty($user['openid']) && $wxuser['id'] == $user['openid']) {
                    $results = ['status' => 1, 'info' => '您已授权，无需重复授权!'];
                    return view(null, ['list' => $results]);
                }
                $res = (new Riderlist())->where(['id' => $user['id']])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败!'];
                    return view(null, ['list' => $results]);
                }
            }
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => $e->getMessage()];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
        return view(null, ['list' => $results]);
    }

    public function order_cat()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'orderid' => 'require',
            'data' => 'require'
        ], [
            'orderid.require' => '订单ID不能为空',
            'data.require' => '数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['orders_id' => $this->request->reder_id, 'id' => $data['orderid']])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 2) {
            $this->result([], 1, '订单状态不可更改数据');
        }
        $data['data'] = json_decode($data['data'], true);
        if (empty($data['data'])) {
            $this->result([], 1, '数据格式错误');
        }
        $orderlogs = [];
        $orderlog = (new Orderlog())->where(['ordersn' => $order['ordersn']])->column('areapriceid');
        foreach ($data['data'] as $datas) {
            if (empty($datas['id']) || empty($datas['num'])) {
                $this->result([], 1, '数据参数错误');
            }
            $datas['num'] = (int)$datas['num'];
            $list = (new AreaPrice())->where(['id' => $datas['id'], 'streetid' => $order['street']])->find();
            if (empty($list)) {
                $list = (new AreaPrice())->where(['id' => $datas['id'], 'areaid' => $order['area']])->find();
            }
            if (empty($list)) {
                $this->result([], 1, '街道、村镇价格不能为0，请重新选择');
            }
            if (!in_array($list['id'], $orderlog)) {
                $orderlogs[] = [
                    'ordersn' => $order['ordersn'],
                    'areapriceid' => $list['id'],
                    'money' =>  $list['price'],
                    'number' => $datas['num'],
                    'icon' => $list['images'],
                    'unit' => $list['unit'],
                    'name' => $list['names']
                ];
            }
        }
        Db::startTrans();
        try {
            if (count($orderlogs) > 0) {
                (new Orderlog())->insertAll($orderlogs);
            }
            Db::commit();
        } catch (\Exception $exception) {
            dump($exception->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败');
        }
        $this->result([], 0, '操作成功');
    }

    public function orderlog_del()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require'
        ], [
            'orderid.require' => 'ID不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $orderlog = (new Orderlog())->where(['id' => $data['id']])->find();
        if (empty($orderlog)) {
            $this->result([], 1, '订单不存在');
        }
        $order = (new Order())->where(['ordersn' => $orderlog['ordersn'], 'orders_id' => $this->request->reder_id])->find();
        if (empty($orderlog)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 2) {
            $this->result([], 1, '订单状态不可更改数据');
        }
        Db::startTrans();
        try {
            (new Orderlog())->where(['id' => $data['id']])->delete();
            Db::commit();
        } catch (\Exception $exception) {
            dump($exception->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败');
        }
        $this->result([], 0, '操作成功');
    }
}
